<template>
  <div>
    <el-button type="success" @click="AddRouter">添加角色</el-button>
    <br>
    <br>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="" type="index" label="编号" align="center" />
      <el-table-column prop="roleName" label="角色名称" align="center">
        <template v-slot="scoped">
          <a href="#" @click="save(scoped.row.roleName, scoped.row.roleId)">{{ scoped.row.roleName }}</a>
        </template>
      </el-table-column>
      <el-table-column prop="createName" label="创建人" align="center" />
      <el-table-column prop="createTime" label="创建日期" align="center">
        <template v-slot="scoped">
          {{ moment(scoped.row.createTime).format("YYYY年MM月DD日 HH:mm:ss") }}
        </template>
      </el-table-column>
      <el-table-column prop="updateName" label="修改人" align="center">
        <template v-slot="scoped">
          <span v-if="!scoped.row.updateName">{{ "--" }}</span>
          <span v-else>{{ scoped.row.updateName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="修改日期" align="center">
        <template v-slot="scoped">
          <span v-if="!scoped.row.updateTime">{{ "--" }}</span>
          <span v-else>{{ moment(scoped.row.updateTime).format("YYYY年MM月DD日 HH:mm:ss") }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="操作" width="160" align="center">
        <template v-slot="scoped">
          <el-link style="margin: 0 3px;" type="warning" size="small"
            @click="UpDateRouter(scoped.row.roleId)">修改</el-link>
          <el-link style="margin: 0 3px;" type="danger" size="small" @click="Del(scoped.row.roleId)">删除</el-link>
          <el-link style="margin: 0 3px;" type="primary" size="small"
            @click="FenPei(scoped.row.roleId, scoped.row.roleName)">分配人员</el-link>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!--角色修改 对话框 -->
  <div>
    <el-dialog v-model="dialogFormVisibleUpdate" title="修改角色" width="500">
      <el-form :model="form">
        <el-form-item label="角色名称" prop="roleName" @change="OneUserName">
          <el-input v-model="form.roleName" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisibleUpdate = false">取消</el-button>
          <el-button type="primary" @click="submitForm">
            修改
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!--角色分配 对话框 -->
  <div>
    <el-dialog v-model="dialogFormVisibleFenPei" width="500">
      <h3 style="margin-bottom: 33px;">请设置<span style="color: red;">【{{ roleNamefen }}】</span>角色的员工</h3>
      <!-- 左右布局 -->
      <div class="common-layout">
        <el-container>
          <el-aside style="height: 300px; width: 200px;">
            <!-- 部门加载 -->
            <div>
              <div>
                <el-tree :data="DepData" show-checkbox node-key="value" ref="treeRef" :props="defaultProps"
                  :default-checked-keys="defaultCheckedKeys" @check-change="handleCheckChange"
                  default-expand-all="true"></el-tree>
              </div>
            </div>
          </el-aside>
          <el-aside style="height: 300px; width: 200px;">
            <!-- 用户根据部门加载 -->
            <div>
              <p style="margin-bottom: 15px;">选择员工</p>
              <el-checkbox-group v-model="userrolevules.userIds">
                <el-checkbox style="display: block;" v-for="items in uservule" :key="items.userId"
                  :label="items.nickName" :value="items.userId" />
              </el-checkbox-group>
            </div>
          </el-aside>
        </el-container>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisibleFenPei = false">取消</el-button>
          <el-button type="primary" @click="RoleUserAdd">
            确定保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <!-- 角色查看用户弹出框 -->
  <div>
    <el-dialog v-model="dialogFormVisible2" title="" width="500">
      <h3>属于角色<span style="color: red;">【{{ roleVlues.roleName }}】</span>的员工如下</h3>
      <el-button type="success" size="small" style="margin-top: 5px;"
        @click="pprole(roleVlues.roleName, roleVlues.roleId)">添加用户</el-button>
      <el-table :data="getUserNamelist" border style="margin-top: 10px;width: 100%">
        <el-table-column prop="nickName" label="员工名称" />
        <el-table-column label="操作">
          <template v-slot="scoped">
            <el-button type="danger" size="small" @click="Delur(scoped.row.userRoleId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible2 = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import axios, { Axios } from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import moment from 'moment';
import { compile, computed, onMounted, reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { useCounterStore } from '@/stores/counter';
import DepData from '@/stores/departmentData'
//pini保存
const store = useCounterStore();
//跳转
const router = useRouter();

//添加条转
const AddRouter = () => {
  router.push("/AddRole")
}




//#region 对话框角色显示================================================================================
//角色对话框开关
const dialogFormVisible2 = ref(false)
const dialogFormVisible = ref(false)
const pproleName = ref("")

//存放用户昵称
const getUserNamelist = ref([])
//分配人员弹出框
const pprole = (roleName: any, roleId: any) => {
  //打开分配角色对话框
  dialogFormVisibleFenPei.value = true
  FenPei(roleId, roleName);
  pproleName.value = roleName;
}

//角色查询id存放
const roleVlues = reactive({
  roleId: 0,
  roleName: "",
})


//1.打开角色显示对话框 2.传值(角色id)查询用户对应名称
const save = (roleName: any, roleId: number) => {
  //角色对话看显示--打开
  dialogFormVisible2.value = true
  roleVlues.roleId = roleId
  roleVlues.roleName = roleName;
  getroleuserList();
}

//通过角色id查询用户名称
const getroleuserList = () => {
  axios.get(`https://localhost:7174/api/Message/GetUserNameRoleId?RoleId=` + roleVlues.roleId).then(res => {
    getUserNamelist.value = res.data.data
  })
}


//删除用户角色
const Delur = (ids: any) => {
  ElMessageBox.confirm(
    '你确定删除吗?',
    '提示',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axios.post("https://localhost:7272/api/Message/RemoveUserRole", {
        "userRoleId": [
          ids
        ]
      }).then(res => {
        if (res.data.code == 204) {
          ElMessage.success(res.data.msg);
          getroleuserList();
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}

//#endregion


//#region对话框角色分配 ================================================================================
//角色分配对话框开关
const dialogFormVisibleFenPei = ref(false)

//树形结构
const defaultProps = {
  children: 'children',
  label: 'label',
}

//部门信息存储
const Depvalue = ref([])

//获取用户信息
const uservule = ref()
//选择保存用户ID
const UserIdvalue = ref()
//树形节点保存
const treeRef = ref()
//部门id查询用户id
const handleCheckChange = () => {
  Depvalue.value = treeRef.value.getCheckedKeys();
  const aa = Depvalue.value.join(",")
  console.log(aa, '选择的部门id')
  axios.get("https://localhost:7174/api/Message/GetUserName", {
    params: {
      DepId: aa
    }
  }).then(res => {
    uservule.value = res.data.data
  })
}

//显示角色名称
const roleNamefen = ref('')

//分配人员
const FenPei = (roleids: any, roleName: any) => {
  dialogFormVisibleFenPei.value = true
  //角色ID 赋值
  userrolevules.value.roleId = roleids
  //显示角色名称赋值
  roleNamefen.value = roleName
  // 清空 defaultCheckedKeys 的方法
  clearCheckedKeys();
  //反填用户名称
  FanTianUserName(roleids);
}

// 设置默认勾选的部门节点的 key 值
const defaultCheckedKeys = ref([]);

//反填用户名称
const FanTianUserName = (roleids: Number) => {
  defaultCheckedKeys.value = []
  Depvalue.value = []
  axios.get(`https://localhost:7174/api/Message/GetUserNameRoleId?RoleId=` + roleids).then(res => {
    const data = res.data.data
    //反填用户
    const userids = data.map((x: any) => x.userId)
    // 设置默认选中的用户ID
    userrolevules.value.userIds = userids
    console.log(userids, '反填用户ids')
    //反填部门
    const depids = data.map((x: any) => x.depId);
    const depIdVule = [...new Set(depids)];
    defaultCheckedKeys.value = depIdVule
  })
}

// 清空 defaultCheckedKeys 的方法
const clearCheckedKeys = () => {
  defaultCheckedKeys.value = [];
  if (treeRef.value) {
    treeRef.value.setCheckedKeys([]);
  }
};

//添加用户角色数据
const userrolevules = ref({
  "roleId": 0,
  "userIds": []
})

//批量添加
const RoleUserAdd = () => {
  pprole;
  console.log(userrolevules.value.roleId, "批量删除的角色id")
  console.log(userrolevules.value.userIds, "批量添加的用户id")
  //第一步删除 通过 角色ID批量删除
  axios.post("https://localhost:7272/api/Message/UserRoleRemoveRange", userrolevules.value).then(res => {
    if (res.data.code == 204) {
      // ElMessage.success(res.data.msg)
    }
  })
  //第二步批量添加
  axios.post('https://localhost:7272/api/Message/UserRoleAddRanges', userrolevules.value).then(res => {
    if (res.data.code == 214) {
      ElMessage.success("人员更新成功")
    } else {
      // ElMessage.success(res.data.msg)
    }
    getroleuserList();
  })
  // //关闭角色对话框
  // dialogFormVisible2.value = false
  // //打开角色对话框
  // dialogFormVisible2.value = true

  //关闭分配对话框
  dialogFormVisibleFenPei.value = false
}

//角色对话框对话框开关
const Off = () => {
  //关闭角色对话框
  dialogFormVisible2.value = false
  //打开角色对话框
  dialogFormVisible2.value = false
}


//#endregion

//#region 修改对话框

//对话框 开关
const dialogFormVisibleUpdate = ref(false)

//参数
const form = reactive({
  "roleId": 0,
  "roleName": "",
  "updateName": store.ccstore.nickName,
  "updateTime": "2025-02-25T01:27:40.524Z",
})


//修改反填
const UpDateRouter = (ids: any) => {
  dialogFormVisibleUpdate.value = true
  axios.get(`https://localhost:7174/api/Message/RoleFanTian?RoleId=` + ids).then(res => {
    form.roleId = res.data.data.roleId
    form.roleName = res.data.data.roleName
    form.updateName = store.ccstore.nickName
  })
}

//姓名唯一验证状态
const Status = reactive({
  OneNameStatu: 1, //1通过名不称重复 2不通过名称重复
})
//姓名唯一验证
const OneUserName = () => {
  axios.get(`https://localhost:7174/api/Message/OneRoleName?RoleName=` + form.roleName).then(res => {
    if (res.data.code == 209) {
      ElMessage.error(res.data.msg)
      return Status.OneNameStatu = 2;
    } else {
      ElMessage.success(res.data.msg)
      return Status.OneNameStatu = 1;
    }
  })
}

//修改事件
const submitForm = () => {
  if (form.roleName == "") {
    ElMessage.error("角色名称不可为空")
    return
  }
  if (Status.OneNameStatu == 2) {
    ElMessage.error("添加失败!!用户名称重复")
    return;
  }
  axios.post("https://localhost:7272/api/Message/RoleUpdate", form).then(res => {
    if (res.data.code == 206) {
      ElMessage.success(res.data.msg)
      dialogFormVisibleUpdate.value = false
      show()
    } else {
      ElMessage.success("修改出错")
    }
  })
}


//#endregion

//#region 角色页面显示
//显示
const tableData = ref([])
const show = () => {
  axios.get('https://localhost:7174/api/Message/GetRole', {}).then(res => {
    tableData.value = res.data.data
  })
}

//#endregion


//#region 角色删除
//角色删除
const Del = (ids: any) => {
  ElMessageBox.confirm(
    '你确定删除吗?',
    '提示',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axios.post("https://localhost:7272/api/Message/DelRole", {
        "roleId": ids
      }).then(res => {
        if (res.data.code == 204) {
          ElMessage.success(res.data.msg);
        } else {
          ElMessage.success(res.data.msg);
        }
        show();
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}

//#endregion


onMounted(() => {
  show();
})

</script>

<style scoped></style>